#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/20 18:03
# @Author  : Tom_zc
# @FileName: majun_helper.py
# @Software: PyCharm
import time
import logging

# from .request_handler import RequestHandler
import request_handler

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


class PoisonHelper:
    poison_url = "{}/api/http/majun-service-forwarding/ci-portal/poison/webhook/pr-scan"
    poison_status_url = "{}/api/http/majun-service-forwarding/ci-portal/poison/webhook/query-pr-results-status"

    def __init__(self, app_token, domain,gitcode_domain, request_handler=request_handler.RequestHandler()):
        self.domain = domain
        self.gitcode_domain = gitcode_domain
        self.request_handler = request_handler
        self.app_token = app_token

    def create_task(self, repo, pr_number):
        body = {
            "prUrl": self.gitcode_domain + "/openUBMC/{}/pull/{}".format(repo, pr_number),
            "apiToken": self.app_token,
        }
        _, resp = self.request_handler.post(self.poison_url.format(self.domain), json_data=body)
        if not str(resp.get("code")).startswith("20"):
            raise Exception("create task failed:{}".format(resp.get("message")))
        return resp["result"]["scanId"]

    def check_task(self, task_id):
        count = 0
        while True:
            body = {
                "scanId": task_id,
                "apiToken": self.app_token,
            }
            _, resp = self.request_handler.post(self.poison_status_url.format(self.domain), json_data=body)
            detail_code = int(resp["code"])
            if detail_code == 200:
                if resp["result"]:
                    logging.info("return codeCheck result:{}".format(resp["result"]))
                    if resp["result"]["isPass"]:
                        return "PASS", resp["result"]["url"]
                    return "Failed", resp["url"]
                logging.info("waiting for return codeCheck result for majun platform and count:{}.....".format(count))
                time.sleep(10)
                count += 1
            else:
                return "Failed", resp["message"]

            if count > 10 * 60 / 5:
                return "Timeout", resp["message"]